package com.hmo.appshop.mamager.config;

import com.hmo.appshop.mamager.dto.commom.CustomAccessDeniedException;
import com.hmo.appshop.mamager.dto.commom.CustomAuthenticationException;
import com.hmo.appshop.mamager.dto.commom.JwtAuthenticationTokenFilter;
import com.hmo.appshop.mamager.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    UserService userService;
    @Autowired
    CustomAuthenticationException authenticationException;
    @Autowired
    CustomAccessDeniedException accessDeniedException;
    @Autowired
    JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Bean
    public PasswordEncoder myEncoder() {
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http

                // 基于token，不需要csrf
                .csrf().disable()

                // 基于token，不需要session
                .sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS).and()

                // 下面开始设置权限
                .authorizeRequests()

                //不需要登陆
                .antMatchers(HttpMethod.GET,"/v2/api-docs","/configuration/ui","/swagger-resources/**","/configuration/**","/swagger-ui.html","/webjars/**")
                .permitAll()
                .antMatchers("/login", "/register")// 对登录注册要允许匿名访问
                .permitAll()
                // 需要登录
                //.antMatchers("/app/*").authenticated()

                .antMatchers("/app/type/*")
                .permitAll()

//                .antMatchers("/**")//测试时全部运行访问
//                .permitAll()

                // 除上面外的所有请求全部放开
                //.anyRequest().permitAll();

                // 除上面外的所有请求需要认证
                .anyRequest().authenticated();
        // 禁用缓存
        http.headers().cacheControl();
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);
        http.exceptionHandling()
                .accessDeniedHandler(accessDeniedException)
                .authenticationEntryPoint(authenticationException);
    }
}
